package com.sdp.irrigation.utils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sdp.irrigation.protocol.CommPackage;

public class CommConstants {

	public static final String SEPARATOR = "#";
	
	public static final String JSON_DELIMITER = "\r\n";
	
	public static final String PROTOCAL_FIELD_KEY_DEV_SN = "devSn";
	
	public static final String PROTOCAL_FIELD_KEY_DEV = "dev";
	
	public static final int QUERY_TIME_OUT = 5;
	
	public static final String PROTOCOL_TYPE_LOGIN = ProtocolTypeEnum.LOGIN.getCode();
	
	public static final String TIME_FORMATTER = "yyMMddHHmmss";
	
	public static String generatePakSn() {
		return String.valueOf(new Date().getTime() / 1000);
	}
	
	public static LocalDateTime pakSn2LocalDateTime(String pakSn) {
		return Instant.ofEpochMilli(Long.valueOf(pakSn) * 1000)
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
	}
	
	public static String getLoginCommPackageDevSn(CommPackage packageData) {
		return packageData.getBody().getString(CommConstants.PROTOCAL_FIELD_KEY_DEV_SN);
	}
	
	public static String getHeartCommPackageDevSn(CommPackage packageData) {
		return packageData.getDevSn();
	}
	
	public static String getAlarmCommPackageDevSn(CommPackage packageData) {
		return packageData.getDevSn();
	}
	
	public static String getQueryBalanceCommPackageDevSn(CommPackage packageData) {
		return packageData.getDevSn();
	}
	
	public static String getVersionCommPackageDevSn(CommPackage packageData) {
		return packageData.getDevSn();
	}
	
	public static String getParamSetCommPackageDevSn(CommPackage packageData) {
		return packageData.getDevSn();
	}
	
	public static String getReportCommPackageDevSn(CommPackage packageData) {
		return packageData.getBody().getString(CommConstants.PROTOCAL_FIELD_KEY_DEV_SN);
	}
	
	public static String getUserCommPackageDevSn(CommPackage packageData) {
		JSONObject devObj = packageData.getBody().getJSONObject(CommConstants.PROTOCAL_FIELD_KEY_DEV);
		if (devObj != null && devObj.containsKey(CommConstants.PROTOCAL_FIELD_KEY_DEV_SN)) {
			return devObj.getString(CommConstants.PROTOCAL_FIELD_KEY_DEV_SN);
		}
		return null;
	}
	
	public static boolean isProvinceIcNo(String icNo) {
		if (!StringUtils.isEmpty(icNo)) {
			String lowerCase = icNo.toLowerCase();
			if (lowerCase.startsWith("ffff") && lowerCase.endsWith("0000")) {
				return false;
			}
		}
		return true;
	}
	
	
	public static void printErrorLog(Exception e, org.slf4j.Logger log) {
		log.error("错误消息为：" + e.getMessage());
		for (StackTraceElement element : e.getStackTrace()) {
			log.error(element.toString());
		}
	}
	
}
